package lte

import (
	"time"

	"gitee.com/thubcc/mobile/utils"
)

type PeakRecord struct {
	t time.Time
	p float64
}

func NewPeakRecord(p float64) *PeakRecord {
	return &PeakRecord{
		t: time.Now(),
		p: p,
	}
}

type PeakRecords struct {
	r    []PeakRecord
	pos  int
	Size int
	init bool
}

func NewPeakRecords(s int) *PeakRecords {
	r := make([]PeakRecord, s)
	return &PeakRecords{
		r:    r,
		pos:  0,
		Size: s,
		init: false,
	}
}

func (r *PeakRecords) IsSynced() (std float64, ok bool) {
	if !r.init {
		ok = true
		return
	}
	l := float64(r.Size)
	var sx, sxx float64
	for _, v := range r.r {
		d := v.p - r.r[0].p
		if d > 9600. {
			d -= 19200.
		}
		if d < -9600. {
			d += 19200.
		}
		sx += float64(d)
		sxx += float64(d * d)
	}
	std = sxx/l - (sx/l)*(sx/l)
	if std > 1000. {
		ok = false
	} else {
		ok = true
	}
	return
}

func (s *PeakRecords) Add(p *PeakRecord) (df, my, sy float64, ok bool) {
	s.r[s.pos] = *p
	s.pos += 1
	ok = false
	if s.pos >= s.Size {
		s.pos = 0
		return s.LMS()
	}
	return
}

func (s *PeakRecords) LMS() (df, my, sy float64, ok bool) {
	var r []utils.XY
	for _, v := range s.r {
		r = append(r, utils.NewXY(v.t.Sub(s.r[0].t).Seconds(), v.p-s.r[0].p))
	}
	var y float64
	df, _, y, sy = utils.Axb(r)
	my = s.r[0].p + y
	ok = true
	return
}

func (s *PeakRecords) Init(p *PeakRecord) {
	s.pos = 0
	s.Add(p)
	for s.pos != 0 {
		s.Add(p)
	}
	s.init = true
}
